package com.lsongh.springboot2.controller;

import com.lsongh.springboot2.entity.Result;
import com.lsongh.springboot2.entity.User;
import com.lsongh.springboot2.service.UserService;
import com.lsongh.springboot2.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    UserService  userService;

    @GetMapping("/user/list")
    public Result<User> getListUser() {
//        return userService.findAll();
        return ResultUtil.success(userService.findAll());
    }
    @GetMapping("/user/findAll")
    public Result<User> getAllUser(@RequestParam("name")String name) {
        List<User> list  = userService.findAll();
        List<User> list1=new ArrayList<>();
        for (User user:list) {
            if(user.getDeleteu() == 0){
                list1.add(user);
            }
        }
        return ResultUtil.success(list1);
    }
    //通过id返回用户所有信息
    @GetMapping("/user/{id}")
    public Result<User> getOneUserById(@PathVariable("id")int id){
        User user = userService.findOne(id);
        if (user == null){
            return ResultUtil.error("未找到该用户");
        }else {
            return ResultUtil.success(user);
        }
    }
    //通过id只返回用户名字
    @GetMapping("/user/name/{id}")
    public Result<User> getUserNameById(@PathVariable("id")int id){
        User user = userService.findOne(id);
        if (user == null){
            return ResultUtil.error("未知");
        }else {
            return ResultUtil.success(user.getName());
        }
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @DeleteMapping("user/delete/{id}")
    public Result<String> DeleteUser(@PathVariable("id")int id){
        userService.delete(id);
        return  ResultUtil.success("删除成功");
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    @PostMapping("user/update")
    public  Result<String> updateUser(@RequestBody User user){
        userService.save(user);
        return  ResultUtil.success("修改成功");
    }

    @GetMapping("user/findUser")
    public Result<User> findUserByType(@RequestParam("type") String type){
        List<User> list = userService.findAllByType(type);
        return  ResultUtil.success(list);
    }


}
